<template>
  <div>
    <div class="telnum">
        <van-cell-group border>
        <van-field v-model="pass" label="验证码" placeholder="请输入验证码" autofocus>
            <template #button>
                <van-button size="small" type="primary" :disabled='btnFlag' @click="sendMsg">{{txt}}</van-button>
            </template>
        </van-field>
        </van-cell-group>
    </div>
     <div class="register">
        <van-button round type="danger" size="large" :disabled='flag' @click="next">下一步</van-button>
      </div>
  </div>
</template>

<script>
import Vue from 'vue';
import { Toast } from 'vant';

Vue.use(Toast);

import { doSendMsg,doCheckCode } from '../../api/user'
export default {
    data () {
        return {
            pass: '',
            txt: '发送验证码',
            time: 60,
            btnFlag:false,
        }
    },
    computed: {
        flag() {
        // 满足输入的内容符合验证码的规则
        if(/^\d{5}$/.test(this.pass)) {
          return false;   //符合规则，按钮显示红色，表示可用
        } else {
          return true;    //不符合规则，按钮是淡红色，表示禁用
        }
      }
    },
    methods: {
        sendMsg() {
            // 页面效果上显示倒计时
            const timer = setInterval (()=>{
                this.time--
                if(this.time==0){
                    clearInterval(timer)
                    this.txt = '重新发送';
                    this.btnFlag = false;
                    this.time = 60;
                } else {
                    this.txt = this.time+'s后';
                    this.btnFlag = true;
                }
            },1000)
            // 现在真实的向后端发送请求获取验证码
            setTimeout(()=>{
                doSendMsg({tel:localStorage.getItem('tel')}).then(res=>{
                    console.log(res.data.data);
                    this.pass = res.data.data
                })
            },1500)
        },
        next() {
            doCheckCode({tel:localStorage.getItem('tel'),telcode:this.pass}).then(res=>{
                console.log(res);
                switch (res.data.code) {
                    case '10007':
                        Toast.fail('验证码输入有误，请重新输入');
                        break;
                    case '200':
                        this.$router.push('/register/three')
                        break;
                    default:
                        break;
                }
            })
        }
    }
}
</script>

<style scoped>
.register {
  width: 75%;
  margin: 30px auto;
}
</style>